package com.example.verifysdk.creatcode;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.verifysdk.AuthUtil;
import com.example.verifysdk.BuildConfig;
import com.example.verifysdk.LogUtil;
import com.example.verifysdk.NetWorkUtils;
import com.example.verifysdk.R;
import com.example.verifysdk.ResponseException;
import com.example.verifysdk.SpHelper;
import com.example.verifysdk.UploadHelper;
import com.example.verifysdk.compare.CompareActivity;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 显示个人信息和头像
 */
public class CreatCodeActivity extends Activity implements CreatCodePresenter.CreatCodeView {
    private static final String TAG = "CreatCodeActivity";

    private static final int TIME_STEP = 60 * 1000;
    private ImageView mBackIv;
    private TextView mTitleTv;
    private TextView mRightActionTv;
    private ImageView mPhotoIv, mCodeIv;
    private long mOldTime;
    private long mNextTime;
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    private String mAppPartner;
    private String mAppPartnerRemark;
    private String mTotp;
    private SpHelper spHelper;
    private int mRetryLoginCount = 0;
    private CreatCodePresenter mCreatCodePresenter;
    private Dialog mRetryCompareDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creat_code);
        initView();
        initData();
    }

    public static void startCode(Activity activity, String partnerId, String userId){
        Bundle bundle = new Bundle();
        bundle.putString("partnerId", partnerId);
        bundle.putString("userId", userId);
        Intent intent = new Intent(activity, CreatCodeActivity.class);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    private void initView() {
        mBackIv = findViewById(R.id.top_bar_back_iv);
        mTitleTv = findViewById(R.id.top_bar_title_tv);
        mRightActionTv = findViewById(R.id.top_bar_right_tv);
        mPhotoIv = findViewById(R.id.head_photo_iv);
        mCodeIv = findViewById(R.id.qr_code_iv);

        mRightActionTv.setText("重新认证");
        mRightActionTv.setVisibility(View.VISIBLE);
        mTitleTv.setText(R.string.scan_code);
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mCodeIv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startUpdate();
                return true;
            }
        });
        mRightActionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRetryCompareDialog();
            }
        });

    }

    private void initData() {
        LogUtil.i(TAG, "---BuildConfig.DEBUG===" + BuildConfig.DEBUG);
        mCreatCodePresenter = new CreatCodePresenter();
        mCreatCodePresenter.setmCreatCodeView(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mAppPartner = bundle.getString("partnerId");
            mAppPartnerRemark = bundle.getString("userId");
            mTotp = bundle.getString("totp");
        }
        LogUtil.i(TAG, "---mAppPartner===" + mAppPartner);
        LogUtil.i(TAG, "---mAppPartnerRemark===" + mAppPartnerRemark);
        LogUtil.i(TAG, "---mTotp===" + mTotp);
        if (TextUtils.isEmpty(mAppPartner) || TextUtils.isEmpty(mAppPartnerRemark)) {
            showToast(getString(R.string.params_error), 0);
            finish();
        }

        if (TextUtils.isEmpty(mTotp)) {
            mTotp = "000000";
        }
        spHelper = new SpHelper(this);
        spHelper.putPartenrRemark(mAppPartnerRemark);

//        showSpInfo(spHelper);
        showHeadPhoto();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                checkTime();
                mHandler.postDelayed(this, 1000);
            }
        };
        startUpdate();
    }

    private void showRetryCompareDialog(){
        if (mRetryCompareDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("是否重新提交照片认证？");
            builder.setPositiveButton("重新认证", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    toRetryCompare();
                }
            });
            builder.setNegativeButton("取消", null);
            mRetryCompareDialog = builder.create();
        }
        if (mRetryCompareDialog.isShowing()){
            return;
        }
        mRetryCompareDialog.show();
    }

    private void toRetryCompare(){
        finish();
        Intent intent = new Intent(this, CompareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("partnerId", mAppPartner);
        bundle.putString("userId", mAppPartnerRemark);
        bundle.putString("totp", "retry");
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void showSpInfo(SpHelper sp) {
        LogUtil.i(TAG, "--showSpInfo-mAppPartnerRemark===" + mAppPartnerRemark);
        LogUtil.i(TAG, "--showSpInfo-SDK_TOKEN===" + sp.getSdkToken());
        LogUtil.i(TAG, "--showSpInfo-SDK_SECRET===" + sp.getSdkSecret());
        LogUtil.i(TAG, "--showSpInfo-SDK_USER_ID===" + sp.getSdkUserId());
        LogUtil.i(TAG, "--showSpInfo-SDK_FACE===" + sp.getSdkFacePh());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        LogUtil.i(TAG, "---onWindowFocusChanged===" + hasFocus);
        if (hasFocus) {
            startUpdate();
        }else {
            stopUpdate();
        }
    }

    private void startUpdate(){
        LogUtil.i(TAG, "---startUpdate===");
        mHandler.removeCallbacks(mRunnable);
        mHandler.postDelayed(mRunnable, 1000);
    }

    private void stopUpdate(){
        LogUtil.i(TAG, "---stopUpdate===");
        mHandler.removeCallbacks(mRunnable);
    }

    //每个时间步进时准备更新二维码
    private void checkTime() {
        mOldTime = System.currentTimeMillis();
        if (mOldTime >= mNextTime) {
            LogUtil.i(TAG, "==============================");
            startQRcodeTask();
        }
        mNextTime = ((mOldTime / TIME_STEP) + 1) * TIME_STEP;
    }

    //开始生成二维码的流程
    private void startQRcodeTask() {
        if (TextUtils.isEmpty(spHelper.getSdkSecret())) {
            LogUtil.i(TAG, "---getSdkSecret.isEmpty==");
            if (netIsConnect()) {
                //本地没有token则登录获取token，登录完成后拿在线码
                mCreatCodePresenter.login(mAppPartner, mAppPartnerRemark, mTotp);
            } else {
                showToast("请联网后操作", Toast.LENGTH_SHORT);
                finish();
            }
        } else {
            LogUtil.i(TAG, "---getSdkSecret.notEmpty==");
            //本地有token则优先获取在线码
            getSecret();
        }
    }

    //在线获取二维码内容
    private void getSecret() {
        if (netIsConnect()) {
            LogUtil.i(TAG, "---getOnlineSecret==net==yes==");
            //有网则获取在线秘钥
            mCreatCodePresenter.getOnlineSecret();
        } else {
            LogUtil.i(TAG, "---getOnlineSecret==net==no==");
            //没网则本地生成秘钥
            creatLocalQRcodeMsg();
        }
    }

    //用本地秘钥生成二维码
    private void creatLocalQRcodeMsg() {
        LogUtil.i(TAG, "---secret===" + spHelper.getSdkSecret());
        int code = AuthUtil.getTotp(spHelper.getSdkSecret());
        LogUtil.i(TAG, "---code===" + code);
        int domain = 1;
        int type = 0;
        String totp = String.format("%1$04d%2$1d%3$s%4$06d", domain, type, spHelper.getSdkUserId(), code);
        LogUtil.i(TAG, "---totp===" + totp);
        String secret = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            secret = Base64.encodeToString(totp.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        } else {
            secret = Base64.encodeToString(totp.getBytes(Charset.forName("UTF-8")), Base64.DEFAULT);
        }
        LogUtil.i(TAG, "---secret===" + secret);
        showQRcode(secret);
    }

    //把秘钥内容显示在二维码上
    private void showQRcode(final String codeMsg) {
        LogUtil.i(TAG, "---showQRcode===" + codeMsg);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(codeMsg)) {
                    QRcodeUtil.creatQRcodeInIv(codeMsg, mCodeIv);
                } else {

                }
            }
        });
        Snackbar.make(mCodeIv, getString(R.string.qrcode_is_update), Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void finish() {
        stopUpdate();
        super.finish();
    }

    private boolean netIsConnect() {
        return NetWorkUtils.isNetworkConnected(this);
    }

    private void showHeadPhoto() {
        String imgUrl = spHelper.getSdkFacePh();
        LogUtil.i(TAG, "---showHeadPhoto==imgUrl=" + imgUrl);
        LogUtil.i(TAG, "---showHeadPhoto==token=" + spHelper.getSdkToken());

        if (TextUtils.isEmpty(imgUrl) || isDestroyed()) {
            return;
        }
        Glide.with(this)
                .load(getImgUrl(UploadHelper.getUrl(this) + "web/file/" + spHelper.getSdkFacePh()))
                .apply(new RequestOptions().placeholder(R.mipmap.person_photo_example_bg)
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(mPhotoIv);
    }

    private GlideUrl getImgUrl(String url) {
        LogUtil.i(TAG, "---getImgUrl===" + spHelper.getSdkToken());
        return new GlideUrl(url, new LazyHeaders.Builder()
                .addHeader("APP_TOKEN", spHelper.getSdkToken()).build());
    }

    //显示toast
    private void showToast(final String toast, final int showMode) {
        LogUtil.i(TAG, "---showToast===" + toast);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(CreatCodeActivity.this, toast, showMode).show();
            }
        });
    }

    private void intentToCompare() {
        Intent intent = new Intent(this, CompareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("partnerId", mAppPartner);
        bundle.putString("userId", mAppPartnerRemark);
        bundle.putString("totp", mTotp);
        bundle.putString("phone", "");
        intent.putExtras(bundle);
        startActivityForResult(intent, 666);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 666) {

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.i(TAG, "---onStop===");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopUpdate();
        LogUtil.i(TAG, "---onDestroy===");
    }

    @Override
    public void getSecretSuccess(String sceret) {
        showQRcode(sceret);
    }

    @Override
    public void onFail(ResponseException e) {
        LogUtil.i(TAG, "---onFail===" + e.toString());
        if (!TextUtils.isEmpty(e.getMessage())){
            showToast(e.getMessage(), Toast.LENGTH_SHORT);
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);
    }

    @Override
    public void loginSuccess(LoginObjBean bean) {
        LogUtil.i(TAG, "---loginSuccess===" + bean.toString());
        spHelper.putLoginInfo(bean);
        startQRcodeTask();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showHeadPhoto();
            }
        });
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    public void userNotRegistered() {
        showToast(getString(R.string.please_submit_info), 0);
        finish();
    }

    @Override
    public void reLogin() {
        if (mRetryLoginCount >= 3){
            finish();
            return;
        }
        mRetryLoginCount++;
        mCreatCodePresenter.login(mAppPartner, mAppPartnerRemark, mTotp);
    }
}
